/*
  * RhyJS
  * Google Code:    http://code.google.com/p/rhy-js/
  * Copyright:      Tristan Maindron
  * Twitter:        http://twitter.com/sepheryn
  * License:        MIT
  *
  *
  * OPEN SOURCE PROJECT BUILT-IN
  *  
  * Reqwest
  * Github:         https://github.com/ded/reqwest
  * Copyright:      Dustin Diaz 2011
  * License:        MIT

  * $script.js v1.3
  * Github:         https://github.com/ded/script.js
  * Copyright:      @ded & @fat - Dustin Diaz, Jacob Thornton 2011
  * Twitter:        http://twitter.com/dedfat
  * License:        MIT

  * micro-selector
  * Github:         https://github.com/fabiomcosta/micro-selector
  * Copyright:      Fabio Miranda Costa
  * Twitter:        http://twitter.com/fabiomiranda
  * License:        MIT-style license
*/
var Rhy = {

};

Rhy.extra = {};
Rhy.extradata = {};Rhy.browser = {
    getStartPos:function(){
        return navigator.userAgent.substring(0, navigator.userAgent.indexOf("(", 0));
    },
    
	getMidPos:function(){
        return navigator.userAgent.substring(navigator.userAgent.indexOf("(", 0), navigator.userAgent.indexOf(")", 0));
    },
    
	getEndPos:function(){
        return navigator.userAgent.substring(navigator.userAgent.indexOf(")", 0));
    },
    
	isInternetExplorer:function(){
        return (this.getMidPos().indexOf("MSIE") != -1);
    },
    
	isSafari:function(){
        var safari = (this.getEndPos().indexOf("Safari") != -1);
        var notChrome = this.isChrome();
        return !notChrome && safari;
    },
    
	isFirefox:function(){
        return (this.getEndPos().indexOf("Firefox") != -1);
    },
    
	isChrome:function(){
        return (this.getEndPos().indexOf("Chrome") != -1);
    }
};

Rhy.config = {};

Rhy.config.manager = {
    merge: function(base, o){
        var result = {};

        for(var i in base){
            result[i] = base[i];
        }
        for(var j in o){
            result[j] = o[j];
        }

        return result;
    },

    encode: function(o){
        var parameters = new Array();
        for(var i in o){
            parameters.push(i + '=' + encodeURIComponent(o[i]));
        }
        return parameters.join('&');
    },
    
    decode: function(o){
        var tokens = o.split('&');
        var result = {};
        
        for(var i in tokens){
            var subtoken = tokens[i].split('=');
            result[subtoken[0]] = subtoken[1];
        }
        
        return result;
    }
};

Rhy.os = {
    isWin: function(){
		return (navigator.userAgent.toLowerCase().indexOf("windows") > -1);
	},

    isMac: function(){
		return (navigator.userAgent.toLowerCase().indexOf("mac") > -1);
	},
    
    isLinux: function(){
        return (navigator.appVersion.indexOf("Linux") != -1);
    },
    
    isUnix: function(){
        return (navigator.appVersion.indexOf("X11") != -1);
    }
};

Rhy.string = {
	ellipsis: function(text, length){
		if(text.length > length){
			var i = text.lastIndexOf(' ', length);
			text = text.substr(0, i) + " ...";
		}
		return text;
	}
};

Rhy.view = {
	GlobalPositioning: {
		getOffsetLeft: function(o){
			var curleft = 0;

			while(o){
				curleft += o.offsetLeft;
				o = o.offsetParent;
			}
			return curleft;
		}
	}
}

Rhy.cookie = {
	set: function(name, value) {
		var expDate = new Date();
		expDate.setTime(expDate.getTime() + (365 * 24 * 3600 * 1000));
		document.cookie = name + "=" + escape(value) + ";expires=" + expDate.toGMTString();
	},
	
	get: function(name) {
		var i = document.cookie.indexOf(name + "=")
		if (i >= 0) {
			i += name.length + 1;
			j = document.cookie.indexOf(";",i);
			if (j < 0) 
				j = document.cookie.length;
			return unescape(document.cookie.substring(i,j));
		}
		return "";
	}
}

Rhy.os = {
    isWin: function(){
		return (navigator.userAgent.toLowerCase().indexOf("windows") > -1);
	},

    isMac: function(){
		return (navigator.userAgent.toLowerCase().indexOf("mac") > -1);
	},
    
    isLinux: function(){
        return (navigator.appVersion.indexOf("Linux") != -1);
    },
    
    isUnix: function(){
        return (navigator.appVersion.indexOf("X11") != -1);
    }
};

!function (window) {

  // require valentine module
  var v = window.v;
  if (!v && (typeof require !== 'undefined')) {
    v = require('valentine');
  }

  var twoHundo = /^20\d$/,
      doc = document,
      byTag = 'getElementsByTagName',
      head = doc[byTag]('head')[0],
      xhr = ('XMLHttpRequest' in window) ?
        function () {
          return new XMLHttpRequest();
        } :
        function () {
          return new ActiveXObject('Microsoft.XMLHTTP');
        };

  var uniqid = 0;
  // data stored by the most recent JSONP callback
  var lastValue;

  function readyState(o, success, error) {
    return function () {
      if (o && o.readyState == 4) {
        if (twoHundo.test(o.status)) {
          success(o);
        } else {
          error(o);
        }
      }
    };
  }

  function setHeaders(http, o) {
    var headers = o.headers || {};
    headers.Accept = headers.Accept || 'text/javascript, text/html, application/xml, text/xml, */*';

    // breaks cross-origin requests with legacy browsers
    if (!o.crossOrigin) {
      headers['X-Requested-With'] = headers['X-Requested-With'] || 'XMLHttpRequest';
    }

    if (o.data) {
      headers['Content-type'] = headers['Content-type'] || 'application/x-www-form-urlencoded';
      for (var h in headers) {
        headers.hasOwnProperty(h) && http.setRequestHeader(h, headers[h], false);
      }
    }
  }

  function getCallbackName(o) {
    var callbackVar = o.jsonpCallback || "callback";
    if (o.url.slice(-(callbackVar.length + 2)) == (callbackVar + "=?")) {
      // Generate a guaranteed unique callback name
      var callbackName = "reqwest_" + uniqid++;

      // Replace the ? in the URL with the generated name
      o.url = o.url.substr(0, o.url.length - 1) + callbackName;
      return callbackName;
    } else {
      // Find the supplied callback name
      var regex = new RegExp(callbackVar + "=([\\w]+)");
      return o.url.match(regex)[1];
    }
  }

  // Store the data returned by the most recent callback
  function generalCallback(data) {
    lastValue = data;
  }

  function getRequest(o, fn, err) {
    if (o.type == 'jsonp') {
      var script = doc.createElement('script');

      // Setup our script element
      script.type = "text/javascript";
      script.src = o.url;
      script.async = true;

      // Add the script to the DOM head
      head.appendChild(script);
    } else {
      var http = xhr();
      http.open(o.method || 'GET', typeof o == 'string' ? o : o.url, true);
      setHeaders(http, o);
      http.onreadystatechange = readyState(http, fn, err);
      o.before && o.before(http);
      http.send(o.data || null);
      return http;
    }
  }

  function Reqwest(o, fn) {
    this.o = o;
    this.fn = fn;
    init.apply(this, arguments);
  }

  function setType(url) {
    if (/\.json$/.test(url)) {
      return 'json';
    }
    if (/\.jsonp$/.test(url)) {
      return 'jsonp';
    }
    if (/\.js$/.test(url)) {
      return 'js';
    }
    if (/\.html?$/.test(url)) {
      return 'html';
    }
    if (/\.xml$/.test(url)) {
      return 'xml';
    }
    return 'js';
  }

  function init(o, fn) {
    this.url = typeof o == 'string' ? o : o.url;
    this.timeout = null;
    var type = o.type || setType(this.url), self = this;
    fn = fn || function () {};

    if (o.timeout) {
      this.timeout = setTimeout(function () {
        self.abort();
        error();
      }, o.timeout);
    }

    function complete(resp) {
      o.complete && o.complete(resp);
    }

    function success(resp) {
      o.timeout && clearTimeout(self.timeout) && (self.timeout = null);
      var r = resp.responseText;

      if (r) {
        switch (type) {
        case 'json':
          resp = window.JSON ? window.JSON.parse(r) : eval('(' + r + ')');
          break;
        case 'js':
          resp = eval(r);
          break;
        case 'html':
          resp = r;
          break;
        // default is the response from server
        }
      }

      fn(resp);
      o.success && o.success(resp);
      complete(resp);
    }

    function error(resp) {
      o.error && o.error(resp);
      complete(resp);
    }

    this.request = getRequest(o, success, error);
  }

  Reqwest.prototype = {
    abort: function () {
      this.request.abort();
    },

    retry: function () {
      init.call(this, this.o, this.fn);
    }
  };

  function reqwest(o, fn) {
    return new Reqwest(o, fn);
  }

  function enc(v) {
    return encodeURIComponent(v);
  }

  function serial(el) {
    var n = el.name;
    // don't serialize elements that are disabled or without a name
    if (el.disabled || !n) {
      return '';
    }
    n = enc(n);
    switch (el.tagName.toLowerCase()) {
    case 'input':
      switch (el.type) {
      // silly wabbit
      case 'reset':
      case 'button':
      case 'image':
      case 'file':
        return '';
      case 'checkbox':
      case 'radio':
        return el.checked ? n + '=' + (el.value ? enc(el.value) : true) + '&' : '';
      default: // text hidden password submit
        return n + '=' + (el.value ? enc(el.value) : '') + '&';
      }
      break;
    case 'textarea':
      return n + '=' + enc(el.value) + '&';
    case 'select':
      // @todo refactor beyond basic single selected value case
      return n + '=' + enc(el.options[el.selectedIndex].value) + '&';
    }
    return '';
  }

  reqwest.serialize = function (form) {
    var inputs = form[byTag]('input'),
        selects = form[byTag]('select'),
        texts = form[byTag]('textarea');
    return (v(inputs).chain().toArray().map(serial).value().join('') +
    v(selects).chain().toArray().map(serial).value().join('') +
    v(texts).chain().toArray().map(serial).value().join('')).replace(/&$/, '');
  };

  reqwest.serializeArray = function (f) {
    for (var pairs = this.serialize(f).split('&'), i = 0, l = pairs.length, r = [], o; i < l; i++) {
      pairs[i] && (o = pairs[i].split('=')) && r.push({name: o[0], value: o[1]});
    }
    return r;
  };

  var old = window.reqwest;
  reqwest.noConflict = function () {
    window.reqwest = old;
    return this;
  };

  // defined as extern for Closure Compilation
  // do not change to (dot) '.' syntax
  window['reqwest'] = reqwest;

}(this);
!function(a,b,c){function s(a,c){var e=b.createElement("script"),f=j;e.onload=e.onerror=e[o]=function(){e[m]&&!/^c|loade/.test(e[m])||f||(e.onload=e[o]=null,f=1,h[a]=2,c())},e.async=1,e.src=a,d.insertBefore(e,d.firstChild)}function q(a,b){p(a,function(a){return!b(a)})}var d=b.getElementsByTagName("head")[0],e={},f={},g={},h={},i="string",j=!1,k="push",l="DOMContentLoaded",m="readyState",n="addEventListener",o="onreadystatechange",p=function(a,b){for(var c=0,d=a.length;c<d;++c)if(!b(a[c]))return j;return 1};!b[m]&&b[n]&&(b[n](l,function u(){b.removeEventListener(l,u,j),b[m]="complete"},j),b[m]="loading");var r=function(a,b,d){function o(){if(!--m){e[l]=1,j&&j();for(var a in g)p(a.split("|"),n)&&!q(g[a],n)&&(g[a]=[])}}function n(a){return a.call?a():e[a]}a=a[k]?a:[a];var i=b&&b.call,j=i?b:d,l=i?a.join(""):b,m=a.length;c(function(){q(a,function(a){h[a]?(l&&(f[l]=1),h[a]==2&&o()):(h[a]=1,l&&(f[l]=1),s(r.path?r.path+a+".js":a,o))})},0);return r};r.get=s,r.ready=function(a,b,c){a=a[k]?a:[a];var d=[];!q(a,function(a){e[a]||d[k](a)})&&p(a,function(a){return e[a]})?b():!function(a){g[a]=g[a]||[],g[a][k](b),c&&c(d)}(a.join("|"));return r};var t=a.$script;r.noConflict=function(){a.$script=t;return this},typeof module!="undefined"&&module.exports?module.exports=r:a.$script=r}(this,document,setTimeout);

(function(global, document){

	var elements,
		parsed,
		parsedClasses,
		parsedPseudos,
		pseudos = {},
		context,
		currentDocument,
		reTrim = /^\s+|\s+$/g;

	var supports_querySelectorAll = !!document.querySelectorAll;

	var $u = function(selector, _context, append){
		elements = append || [];
		context = _context || $u.context;
		if (supports_querySelectorAll){
			try{
				arrayFrom(context.querySelectorAll(selector));
				return elements;
			} catch (e){}
		}

		currentDocument = context.ownerDocument || context;
		parse(selector.replace(reTrim, ''));
		find();

		return elements;
	};

	var matchSelector = function(node){
		if (parsed.tag){
			var nodeName = node.nodeName.toUpperCase();
			if (parsed.tag == '*'){
				if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
			} else {
				if (nodeName != parsed.tag) return false;
			}
		}

		if (parsed.id && node.getAttribute('id') != parsed.id){
			return false;
		}

		if ((parsedClasses = parsed.classes)){
			var className = (' ' + node.className + ' ');
			for (var i = parsedClasses.length; i--;){
				if (className.indexOf(' ' + parsedClasses[i] + ' ') < 0) return false;
			}
		}

		if ((parsedPseudos = parsed.pseudos)){
			for (var i = parsedPseudos.length; i--;){
				var pseudoClass = pseudos[parsedPseudos[i]];
				if (!(pseudoClass && pseudoClass.call($u, node))) return false;
			}
		}

		return true;
	};

	var find = function(){

		var parsedId = parsed.id,
			merge = ((parsedId && parsed.tag || parsed.classes || parsed.pseudos)
				|| (!parsedId && (parsed.classes || parsed.pseudos))) ?
				arrayFilterAndMerge : arrayMerge;

		if (parsedId){

			var el = currentDocument.getElementById(parsedId);
			if (el && (currentDocument === context || contains(el))){
				merge([el]);
			}

		} else {

			merge(context.getElementsByTagName(parsed.tag || '*'));

		}

	};

	var parse = function(selector){
		parsed = {};
		while ((selector = selector.replace(/([#.:])?([^#.:]*)/, parser))){};
	};

	var parser = function(all, simbol, name){
		if (!simbol){
			parsed.tag = name.toUpperCase();
		} else if (simbol == '#'){
			parsed.id = name;
		} else if (simbol == '.'){
			if (parsed.classes){
				parsed.classes.push(name);
			} else {
				parsed.classes = [name];
			}
		} else if (simbol == ':'){
			if (parsed.pseudos){
				parsed.pseudos.push(name);
			} else {
				parsed.pseudos = [name];
			}
		}
		return '';
	};

	var slice = Array.prototype.slice;
	var arrayFrom = function(collection){
		elements = slice.call(collection, 0);
	};
	var arrayMerge = function(collection){
		for (var i = 0, node; node = collection[i++];){
			elements.push(node);
		}
	};
	try {
		slice.call(document.documentElement.childNodes, 0);
	} catch(e) {
		arrayFrom = arrayMerge;
	}

	var arrayFilterAndMerge = function(found){
		for (var i = 0, node; node = found[i++];){
			if (matchSelector(node)) elements.push(node);
		}
	};

	var contains = function(node){
		do {
			if (node === context) return true;
		} while ((node = node.parentNode));
		return false;
	};

	$u['pseudos'] = pseudos;
	$u['context'] = document;
	global['uSelector'] = $u;
	if (!global['$u']) global['$u'] = $u;

})(this, document);

(function(){

	var pseudos = {
		empty: function(node){
			var child = node.firstChild;
			return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
		},
		'first-child': function(node){
			while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
			return true;
		},
		'last-child': function(node){
			while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
			return true;
		},
		'only-child': function(node){
			return this.pseudos['first-child'](node) && this.pseudos['last-child'](node);
		},
		'first-of-type': function(node){
			var nodeName = node.nodeName;
			while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
			return true;
		},
		'last-of-type': function(node){
			var nodeName = node.nodeName;
			while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
			return true;
		},
		'only-of-type': function(node){
			return this.pseudos['first-of-type'](node) && this.pseudos['last-of-type'](node);
		},
		disabled: function(node){
			return node.disabled;
		},
		checked: function(node){
			return node.checked || node.selected;
		},
		selected: function(node){
			return node.selected;
		}
	};

	for (var pseudo in pseudos){
		$u.pseudos[pseudo] = pseudos[pseudo];
	}

})();

Rhy.select = $u;
$rh = $u;
Rhy.ajax = reqwest;
Rhy.dependency = {};
Rhy.dependency.load = $script;
Rhy.dependency.ready = $script.ready;
